package org.example.test02.window;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import io.reactivex.Flowable;
import org.example.test02.utils.AliChatUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class ToolWindowChat implements ToolWindowFactory {
    private static StringBuilder fullContent = new StringBuilder();
    // 中间的内容展示框
    private static JEditorPane chatArea = new JEditorPane("text/html", "<html><body></body></html>");
    private static String userInput = "";
    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());


        chatArea.setEditable(false);
        chatArea.setBackground(Color.WHITE);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 下方的输入面板
        JPanel inputPanel = new JPanel(new BorderLayout());
        JTextField inputField = new JTextField();
        inputField.setBackground(Color.WHITE);
        JButton sendButton = new JButton("发送");

        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        mainPanel.add(inputPanel, BorderLayout.SOUTH);

        List<Message> messages = new ArrayList<>();
        messages.add(AliChatUtil.createMessage(Role.SYSTEM, "You are a helpful assistant."));
        // 处理发送按钮点击事件
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                userInput = inputField.getText();
                if (!userInput.isEmpty()) {
                    //将用户说的话放到列表
                    messages.add(AliChatUtil.createMessage(Role.USER, userInput));

//                    Generation gen = new Generation();
//                    GenerationParam param = buildGenerationParam(messages);
//                    try {
//                        //发送流式请求
//                        Flowable<GenerationResult> result = gen.streamCall(param);
//                        //遍历返回的结果，并放到对应全局变量fullContent中，然后放到对话框中
//                        result.blockingForEach(message -> handleGenerationResult(message));
//
//                    } catch (NoApiKeyException ex) {
//                        throw new RuntimeException(ex);
//                    } catch (InputRequiredException ex) {
//                        throw new RuntimeException(ex);
//                    }



                    // 向阿里请求
                    GenerationParam param = AliChatUtil.createGenerationParam(messages);
                    GenerationResult result = null;
                    try {
                        result = AliChatUtil.callGenerationWithMessages(param);
                    } catch (NoApiKeyException ex) {
                        throw new RuntimeException(ex);
                    } catch (InputRequiredException ex) {
                        throw new RuntimeException(ex);
                    }
                    String backendResponse = result.getOutput().getChoices().get(0).getMessage().getContent();
                    updateWindow(backendResponse);

                    //如果历史对话超过三轮，那么删除最早的问题
                    if (messages.size()>3){
                        messages.remove(0);
                    }

                    inputField.setText("");
                }
            }
        });

        // 将主面板添加到 ToolWindow
        ContentFactory contentFactory = ContentFactory.getInstance();
        Content content = contentFactory.createContent(mainPanel, "", false);
        toolWindow.getContentManager().addContent(content);
    }

    private static GenerationParam buildGenerationParam(List<Message> userMsg) {
        return GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey("sk-5bffade0f3fb46d49abf169956ca460e")
                .model("qwen-plus")   // 此处以qwen-plus为例，您可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .messages(userMsg)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }

    private static void handleGenerationResult(GenerationResult message) {
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
        fullContent.append(content);
        System.out.println(content);

        //更新对话框
        //流式请求，请求后将返回的结果解析，更新后端的数据，放到对话框里面
        // 显示用户输入
        String userHtml = "<p style='text-align:right;'>" + userInput + " </p>";
        // 显示后端返回内容
        String backendHtml = "<p style='text-align:left;'>ChatRobot:<br>" + fullContent + "</p>";
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // 获取当前的 HTML 内容
                String currentHtml = chatArea.getText();
//                System.out.println("currentHtml: "+currentHtml);
                // 去掉 HTML 尾部的 </body></html>
                currentHtml = currentHtml.replaceAll("</body>", " ");
                currentHtml = currentHtml.replaceAll("</html>", " ");
//                System.out.println("temp: "+currentHtml);
//                System.out.println("------");
                // 拼接新的内容
                String newHtml = currentHtml + userHtml +"<br></br>"+ backendHtml + "</body></html>";
//                System.out.println(newHtml);
                System.out.println("=======");
                chatArea.setText(newHtml);
            }
        });

    }

    public static void updateWindow(String result){
        //更新对话框
        //流式请求，请求后将返回的结果解析，更新后端的数据，放到对话框里面
        // 显示用户输入
        String userHtml = "<p style='text-align:right;'>" + userInput + " </p>";
        // 显示后端返回内容
        String backendHtml = "<p style='text-align:left;'>ChatRobot:<br>" + result + "</p>";
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // 获取当前的 HTML 内容
                String currentHtml = chatArea.getText();
//                System.out.println("currentHtml: "+currentHtml);
                // 去掉 HTML 尾部的 </body></html>
                currentHtml = currentHtml.replaceAll("</body>", " ");
                currentHtml = currentHtml.replaceAll("</html>", " ");
//                System.out.println("temp: "+currentHtml);
//                System.out.println("------");
                // 拼接新的内容
                String newHtml = currentHtml + userHtml +"<br></br>"+ backendHtml + "</body></html>";
//                System.out.println(newHtml);
                System.out.println("=======");
                chatArea.setText(newHtml);
            }
        });
    }
}
